//
//  PhotoLibViewController.m
//  XPhoto
//
//  Created by baboy on 2019/6/3.
//  Copyright © 2019 baboy. All rights reserved.
//

#import "PhotoLibViewController.h"
#import "PhotoAsset.h"
#import "PhotoSelectionViewCell.h"
#import "PHAsset+x.h"
#import <BKKit/NSDate+x.h>
#import "PhotoLibPreviewViewController.h"
#define ITEM_MARGIN 5
#define NUM_OF_ROW 4
#define REUSE_CELL_ID @"photo_selection_view_cell"


@interface PhotoLibViewController ()<PhotoLibPreviewDelegate, PhotoSelectionViewCellDelegate>
{
    NSMutableArray<PHAsset*>* _selectedAssets;
}
@property(nonatomic, strong) PHFetchResult* photos;
@property(nonatomic, assign) CGSize itemSize;
@property(nonatomic, assign) BOOL shouldSelectPhoto;
@property(nonatomic, assign) BOOL shouldSelectVideo;
@end

@implementation PhotoLibViewController

- (id)init{
    if (self = [self initWithNibName:NSStringFromClass([self class]) bundle:nil]) {
        self.selectionOneType = YES;
        self.maxSelectedCount = 36;
        self.maxVideoCount = -1;
        self.maxPhotoCount = -1;
        self.shouldSelectPhoto = YES;
        self.shouldSelectVideo = YES;
        self.edit = YES;
    }
    return self;
}
- (UICollectionViewFlowLayout*)collectViewFlowLayout{
    
    CGFloat itemWidth = (self.collectionView.bounds.size.width - (NUM_OF_ROW+1)*ITEM_MARGIN)/NUM_OF_ROW;
    
    UICollectionViewFlowLayout * flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.minimumLineSpacing = ITEM_MARGIN;
    flowLayout.minimumInteritemSpacing = ITEM_MARGIN;
    flowLayout.itemSize = CGSizeMake(itemWidth, itemWidth);;
//    flowLayout.sectionInset = UIEdgeInsetsMake(ITEM_MARGIN, ITEM_MARGIN,ITEM_MARGIN, ITEM_MARGIN);
    return flowLayout;
}
- (void)initNavigationBar{
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"cancel", @"按钮")
                                                                             style:UIBarButtonItemStyleDone
                                                                            target:self
                                                                            action:@selector(goBack:)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"next", @"按钮")
                                                                             style:UIBarButtonItemStyleDone
                                                                            target:self
                                                                            action:@selector(done:)];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Do any additional setup after loading the view from its nib.
    [self initNavigationBar];
    
    _selectedAssets = [NSMutableArray array];
    [self selectedAssetsChanged];
    
    self.collectionView.collectionViewLayout = [self collectViewFlowLayout];
    [self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([PhotoSelectionViewCell class]) bundle:nil] forCellWithReuseIdentifier:REUSE_CELL_ID];
    dispatch_async(dispatch_get_main_queue(), ^{
        int mediaType = PHAssetMediaTypeUnknown;
        if (self.maxVideoCount == 0) {
            mediaType = PHAssetMediaTypeImage;
        }
        if (self.maxPhotoCount == 0) {
            mediaType = PHAssetMediaTypeVideo;
        }
        self.photos = [PHAsset fetchAllAssetsWithMediaType:mediaType soryByCreationDateAsc:YES];
        [self.collectionView reloadData];
//        DLOG(@"%@", NSStringFromCGSize(self.collectionView.collectionViewLayout.collectionViewContentSize));
//        CGPoint bottomOffset = CG[PointMake(0, self.collectionView.contentSize.height -     self.collectionView.bounds.size.height);
        [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:[self.photos count]-1 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
    });
}
/**
 * 指定类型是否只能选择一个
 */
- (BOOL) shouldSelectWithAsset:(PHAsset*)asset{
    //已经选中
    if ([self isSelected:asset]) {
        return YES;
    }
    if( asset.mediaType == PHAssetMediaTypeImage && self.shouldSelectPhoto){
        return YES;
    }
    if( asset.mediaType == PHAssetMediaTypeVideo && self.shouldSelectVideo){
        return YES;
    }
    return NO;
}
- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    
    CGFloat itemWidth = (self.collectionView.frame.size.width - (NUM_OF_ROW+1)*ITEM_MARGIN)/NUM_OF_ROW;
    UICollectionViewFlowLayout * flowLayout = (UICollectionViewFlowLayout *)self.collectionView.collectionViewLayout;
    flowLayout.itemSize = CGSizeMake(itemWidth, itemWidth);
}
- (BOOL)isSelected:(PHAsset *)asset{
    for (int i = 0; i<_selectedAssets.count; i++) {
        PHAsset *a = [_selectedAssets objectAtIndex:i];
        if([a.localIdentifier isEqualToString:asset.localIdentifier]){
            return YES;
        }
    }
    return NO;
}
- (void)selectedAssetsChanged{
    NSInteger n = self.selectedAssets.count;
    //总数选满了
    if (n >= self.maxSelectedCount) {
        self.shouldSelectPhoto = NO;
        self.shouldSelectVideo = NO;
        return;
    }
    NSInteger selectedVideoCount = 0;
    NSInteger selectedPhotoCount = 0;
    for (PHAsset *asset in self.selectedAssets) {
        if (asset.mediaType == PHAssetMediaTypeImage) {
            selectedPhotoCount ++;
        }
        if (asset.mediaType == PHAssetMediaTypeVideo) {
            selectedVideoCount ++;
        }
    }
    //只能选一种
    BOOL shouldSelectPhoto = YES;
    BOOL shouldSelectVideo = YES;

    if (self.selectionOneType) {
        //已经选过照片，或者什么也没选
        shouldSelectPhoto = selectedPhotoCount > 0 || (selectedPhotoCount + selectedVideoCount) == 0;
        //已经选过视频，或者什么也没选
        shouldSelectVideo = selectedVideoCount > 0 || (selectedPhotoCount + selectedVideoCount) == 0;
    }
    if (self.maxPhotoCount >= 0) {
        shouldSelectPhoto = shouldSelectPhoto && self.maxPhotoCount > selectedPhotoCount;
    }
    if (self.maxVideoCount >= 0) {
        shouldSelectVideo = shouldSelectVideo && self.maxVideoCount > selectedVideoCount;
    }
    BOOL reload = NO;
    if (self.shouldSelectPhoto != shouldSelectPhoto || self.shouldSelectVideo!=shouldSelectVideo) {
        reload = YES;
    }
    self.shouldSelectPhoto = shouldSelectPhoto;
    self.shouldSelectVideo = shouldSelectVideo;
    if (reload) {
        [self.collectionView reloadData];
    }
}
- (BOOL)selectAsset:(PHAsset*)asset{
    //如果已经选中
    if ([self isSelected:asset]) {
        return NO;
    }
    //如果只能选一个，则清空列表
    if (self.maxSelectedCount == 1) {
        [_selectedAssets removeAllObjects];
    }
    //该类型已经选满
    if ( (!self.shouldSelectPhoto && asset.mediaType == PHAssetMediaTypeImage) ||
        (!self.shouldSelectVideo && asset.mediaType == PHAssetMediaTypeVideo)) {
        return NO;
    }
    [_selectedAssets addObject:asset];
    [self selectedAssetsChanged];
    
    //托管已经选中
    if(self.delegate && [self.delegate respondsToSelector:@selector(photoLibViewController:didSelectAsset:)]){
        [self.delegate photoLibViewController:self didSelectAsset:asset];
    }
    return YES;
}
- (void)deselectAsset:(PHAsset*)asset{
    for (int i = 0; i<_selectedAssets.count; i++) {
        PHAsset *a = [_selectedAssets objectAtIndex:i];
        if([a.localIdentifier isEqualToString:asset.localIdentifier]){
            [_selectedAssets removeObjectAtIndex:i];
            if(self.delegate && [self.delegate respondsToSelector:@selector(photoLibViewController:didDeselectAsset:)]){
                [self.delegate photoLibViewController:self didDeselectAsset:a];
            }
            [self selectedAssetsChanged];
            break;
        }
    }
}
#pragma mark - UICollectionViewDataSource
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _photos.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    DLOG(@"indexPath:%ld, %ld", indexPath.item, self.photos.count)
    PHAsset *asset = self.photos[indexPath.item];
    PhotoSelectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:REUSE_CELL_ID forIndexPath:indexPath];
    cell.delegate = self;
    cell.checkbox.selected = [self isSelected:asset];
    if (asset.mediaType == PHAssetMediaTypeVideo) {
        cell.durationLabel.text = [[NSDate dateWithTimeIntervalSince1970:asset.duration] format:@"mm:ss"];
        cell.durationLabel.hidden = NO;
    }
    //只能选择一个则不显示复选框
    cell.checkbox.hidden = self.maxSelectedCount == 1;
//    if ([self shouldSelectOnlyOneAssetWithType:asset.mediaType]) {
//        cell.checkbox.hidden = YES;
//    }
    cell.maskView.hidden = [self shouldSelectWithAsset:asset];

    CGSize itemSize = ((UICollectionViewFlowLayout*)collectionView.collectionViewLayout).itemSize;
#pragma mark - 单张缩略图
    [[PHCachingImageManager defaultManager] requestImageForAsset:asset
                                                      targetSize:itemSize contentMode:PHImageContentModeAspectFill
                                                         options:nil
                                                   resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
                                                       
                                                       [cell.imageView setImage:result];
//                                                       DLOG(@"image info:%@", info);
                                                   }];
    cell.tag = indexPath.row;
    return cell;
}

#pragma mark- 单张图片
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.maxSelectedCount == 1) {
        
        PHAsset *asset = [self.photos objectAtIndex:indexPath.item];
        [self selectAsset:asset];
        [self done:nil];
        return;
    }
    DLOG(@"selectAtIndex:%ld, %ld", indexPath.item, self.photos.count);
    PhotoLibPreviewViewController *vc = [[PhotoLibPreviewViewController alloc] init];
    vc.photos = self.photos;
    vc.delegate = self;
    vc.currentIndex = indexPath.item;
    vc.photoCount = self.photos.count;
    vc.showCheckbox = self.maxSelectedCount > 1;
    vc.selectedPhotos = [NSMutableArray arrayWithArray:self.selectedAssets];
    [[self navigationController] pushViewController:vc animated:YES];
}
#pragma mark - PhotoSelectionViewCellDelegate
- (void)photoSelectionViewCellDidClickCheckbox:(PhotoSelectionViewCell *)cell{
    if ( cell.maskView.hidden ){
        PHAsset *asset = self.photos[cell.tag];
        if (!cell.checkbox.selected || self.maxSelectedCount == 1) {
            BOOL f = [self selectAsset:asset];
            if (f) {
                cell.checkbox.selected = YES;
            }
        }else{
            [self deselectAsset:asset];
            cell.checkbox.selected = NO;
        }
    }
}
#pragma mark - PhotoLibPreviewDelegate
//- (PHAsset*)photoLibPreviewViewController:(PhotoLibPreviewViewController *)vc loadPhotoAtIndex:(NSInteger)index{
//    return [self.photos objectAtIndex:index];
//}
//- (NSInteger)photoLibPreviewViewController:(PhotoLibPreviewViewController *)vc indexOfPhoto:(PHAsset *)photoAsset{
//    return [self.photos indexOfObject:photoAsset];
//}
- (BOOL)photoLibPreviewViewController:(PhotoLibPreviewViewController *)vc selectAsset:(PHAsset *)asset{
//    PHAsset *asset = self.photos[index];
    BOOL ret = [self selectAsset:asset];
    if (ret) {
        NSInteger index = [self.photos indexOfObject:asset];
        [self.collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:index inSection:0]]];
    }
    return ret;
}
- (BOOL)photoLibPreviewViewController:(PhotoLibPreviewViewController *)vc deselectAsset:(PHAsset *)asset{
//    PHAsset *asset = self.photos[index];
    [self deselectAsset:asset];
    NSInteger index = [self.photos indexOfObject:asset];
    [self.collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:index inSection:0]]];
    return YES;
}
- (BOOL)photoLibPreviewViewController:(PhotoLibPreviewViewController *)vc shouldSelectAsset:(PHAsset *)asset{
//    PHAsset *photoAsset = [self.photos objectAtIndex:index];
    BOOL shouldSelect = [self shouldSelectWithAsset:asset];
    return shouldSelect;
}
- (void)photoLibPreviewViewController:(PhotoLibPreviewViewController*)vc didFinishAtIndex:(NSInteger)index{
    [self editWithSelectedAssets];
    
    if( self.maxSelectedCount == 1){
        [_selectedAssets removeAllObjects];
        [self selectedAssetsChanged];
        PHAsset *asset = self.selectedAssets.firstObject;
        [vc removeSelectedPhoto:asset];
        [self.collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:index inSection:0]]];
    }
}

#pragma button actions
- (void)goBack:(id)button{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
- (void)editWithSelectedAssets{
    if (self.edit) {
        PhotoEditViewController *photoEditViewController = [[PhotoEditViewController alloc] initWithAssets:self.selectedAssets];
        photoEditViewController.delegate = self;
        [self.navigationController pushViewController:photoEditViewController animated:YES];
    }
    if (!self.edit && self.delegate) {
        NSMutableArray *photos = [NSMutableArray array];
        for (NSInteger i = 0, n = self.selectedAssets.count; i < n; i++) {
            PhotoAsset *photoAsset = [PhotoAsset new];
            photoAsset.asset = [self.selectedAssets objectAtIndex:i];
            [photos addObject:photoAsset];
        }
        [self.delegate photoLibViewController:self didSelectPhotos:photos];
    }
}
- (IBAction)done:(id)sender{
    if (!self.selectedAssets || self.selectedAssets.count == 0) {
        return;
    }
    [self editWithSelectedAssets];
    
    PHAsset *asset = self.selectedAssets.firstObject;
    if( self.maxSelectedCount == 1 ||
       (asset.mediaType == PHAssetMediaTypeVideo && self.maxVideoCount == 1) ||
       (asset.mediaType == PHAssetMediaTypeImage && self.maxPhotoCount == 1)){
        [_selectedAssets removeAllObjects];
        [self selectedAssetsChanged];
        
        NSInteger index = [self.photos indexOfObject:asset];
        [self.collectionView reloadItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:index inSection:0]]];
    }
}
- (void)photoEditViewController:(id)controller didEditPhotos:(NSArray *)photoAssets{
    [self.delegate photoLibViewController:self didSelectPhotos:photoAssets];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (void)photoSelectionView:(id)view didSelectPhotos:(NSArray *)photos{
//    self.descLabel.text = [NSString stringWithFormat:NSLocalizedString(@"photo_selected_count_desc_format", @"描述"),photos.count];
//    if (photos.count == self.maxSelectedCount && self.autoNextStep) {
//        [self nextStep:nil];
//    }
}
@end
